const WXAPI = require('apifm-wxapi')
const CONFIG = require('../../config.js')
const SETGOODS = require('../../utils/setgoos.js')
const AUTH = require('../../utils/auth')
//获取应用实例
var app = getApp()
Page({
  data: {
    hasShop: false,
    inputShowed: false, // 是否显示搜索框
    inputVal: "", // 搜索框内容
    category_box_width: 750, //分类总宽度
    // goodsRecommend: [], // 推荐商品
    // kanjiaList: [], //砍价商品列表
    // pingtuanList: [], //拼团商品列表

    loadingHidden: false, // loading
    userInfo: {},
    selectCurrent: 0,
    categories: [],
    activeCategoryId: 0,
    goods: [],
    
    scrollTop: 0,
    loadingMoreHidden: true,

    coupons: [],

    curPage: 1,
    pageSize: 10,
    cateScrollTop: 0,
    shops:[],
    shopListShow:false,//更多商铺
    promptText:'',//公告

  },
  getRecentShop(){
    let that = this;
    WXAPI.getRecentShop().then(function (res) {
      if(res.retCode == '200'){
        that.setData({
          shops: res.data,
        });
      }else{
        that.setData({
          shops: [],
        });
      }
    })
  },
  showMoreShops(){

    this.setData({
      shopListShow:true,
    })
  },
  closeCover(){
    this.setData({
      shopListShow: false,
    })
  },

  tabClick: function(e) {
    let offset = e.currentTarget.offsetLeft;
    if (offset > 150) {
      offset = offset - 150
    } else {
      offset = 0;
    }
    this.setData({
      activeCategoryId: e.currentTarget.id,
      curPage: 1,
      cateScrollTop: offset
    });

    this.getShowItemByCatNo(this.data.activeCategoryId);
    // this.getGoodsList(this.data.activeCategoryId);
  },
  toDetailsTap: function(e) {
    console.log(e.currentTarget.dataset.id)
    wx.navigateTo({
      url: "/pages/goods-details/index?id=" + e.currentTarget.dataset.id
    })
  },
  tapBanner: function(e) {
    if (e.currentTarget.dataset.id != 0) {
      wx.navigateTo({
        url: "/pages/goods-details/index?id=" + e.currentTarget.dataset.id
      })
    }
  },
  bindTypeTap: function(e) {
    this.setData({
      selectCurrent: e.index
    })
  },
  toOpen(){
    wx.navigateTo({
      url: "/pages/new-shop/index"
    })
  },
  onShow () {
    AUTH.checkHasLogined().then(isLogined => {
      if (isLogined) {
        if(wx.getStorageSync('_curShop') && wx.getStorageSync('_curShop').shopNo){
          this.setData({
            hasShop: true
          })
          this.downShow()
          
        }else{
          this.setData({
            hasShop: false
          })
        }
        
      } else {
        wx.showModal({
          title: '提示',
          content: '本次操作需要您的登录授权',
          cancelText: '暂不登录',
          confirmText: '前往登录',
          success(res) {
            if (res.confirm) {
              wx.switchTab({
                url: "/pages/my/index"
              })
            } else {
              wx.switchTab({
                url: "/pages/my/index"
              })
            }
          }
        })
      }
    })    
  },
  downShow: function(e) {   
    wx.showShareMenu({
      withShareTicket: true
    }) 
    const that = this
    // if (e && e.query && e.query.inviter_id) { 
    //   wx.setStorageSync('referrer', e.query.inviter_id)
    // }
    // if (e && e.scene) {
    //   const scene = decodeURIComponent(e.scene)
    //   if (scene) {        
    //     wx.setStorageSync('referrer', scene.substring(11))
    //   }
    // }
    wx.setNavigationBarTitle({
      title: '店铺'
    })
    WXAPI.goodsCategory().then(function(res) {
      let categories = [{
        catNo: 0,
        icon: '/images/fl.png',
        catName: "全部"
      }];
      // let categories = [];
      if (res.retCode == 200) {
        categories = categories.concat(res.data)
      }
      // const _n = Math.ceil(categories.length / 2)
      const _n = categories.length ;
      that.setData({
        categories: categories,
        category_box_width: 140 * _n,
        activeCategoryId: 0,
        curPage: 1
      });
      // console.log(that.data.categories)
      that.seachGoodsList(''); 
      that.getRecentShop(); 
    })
    // that.getRandomItem()
    that.getNotice()
    // that.kanjiaGoods()
    // that.pingtuanGoods()
    app.getGoodsNo();
  },
  
  onPageScroll(e) {
    // let scrollTop = this.data.scrollTop
    console.log(e.scrollTop)
    this.setData({
      scrollTop: e.scrollTop
    })
  },
  // getRandomItem(){
  //   const that = this;
  //   WXAPI.randomItem().then(function(res) {
  //     if (res.retCode === '200'){
  //       console.log(res.data)
  //       that.setData({
  //         goodsRecommend: res.data
  //       })
  //     }
  //   })
  // },
  // getGoodsList: function(categoryId, append) {
  //   if (categoryId == 0) {
  //     categoryId = "";
  //   }
  //   var that = this;
  //   wx.showLoading({
  //     "mask": true
  //   })
  //   WXAPI.randomItem().then(function(res) {
  //     wx.hideLoading()
  //     if (!res.retCode||res.retCode!=200) {
  //       let newData = {
  //         loadingMoreHidden: false
  //       }
  //       // if (!append) {
  //       //   newData.goods = []
  //       // }
  //       that.setData(newData);
  //       return
  //     }
  //     let goods = [];
  //     // if (append) {
  //     //   goods = that.data.goods
  //     // }
  //     for (var i = 0; i < res.data.length; i++) {
  //       goods.push(res.data[i]);
  //     }
  //     that.setData({
  //       loadingMoreHidden: true,
  //       goods: goods,
  //     });
  //   })
  // },


  getShowItemByCatNo(no) {
    var that = this;
    wx.showLoading({
      "mask": true
    })
    
    WXAPI.getGoodsByCat(no).then(function (res) {
      wx.hideLoading()
      if (res.retCode !== '200') {
        let newData = {
          loadingMoreHidden: false
        }
        that.setData(newData);
        return
      }
      let goods = [];
      // if (no) {
      //   goods = that.data.goods
      // }
      for (var i = 0; i < res.data.length; i++) {
        goods.push(res.data[i]);
      }
      that.setData({
        loadingMoreHidden: true,
        goods: goods,
      });
    })
  },

  // getFindChildItemCatByNo(no){
  //   var that = this;
  //   wx.showLoading({
  //     "mask": true
  //   })
  //   WXAPI.goodsCatItem({
  //     catNo: no,
  //   }).then(function (res) {
  //     wx.hideLoading()
  //     if (res.retCode !== '200') {
  //       let newData = {
  //         loadingMoreHidden: false
  //       }
  //       that.setData(newData);
  //       return
  //     }
  //     let goods = [];
  //     if (append) {
  //       goods = that.data.goods
  //     }
  //     for (var i = 0; i < res.data.list.length; i++) {
  //       goods.push(res.data.list[i]);
  //     }
  //     that.setData({
  //       loadingMoreHidden: true,
  //       goods: goods,
  //     });
  //   })
  // },
  seachGoodsList: function (append) {
    var that = this;
    wx.showLoading({
      "mask": true
    })
    WXAPI.goods({
      //categoryId: categoryId,
      // keyWords: that.data.inputVal,
      keyWords: append,
      pageNum: this.data.curPage,
      pageSize: this.data.pageSize
    }).then(function (res) {
      wx.hideLoading()
      if (res.retCode !== '200') {
        let newData = {
          loadingMoreHidden: false
        }
        that.setData({...newData,goods:[]});
        return
      }
      let goods = [];
      if (append) {
        goods = that.data.goods
      }
      for (var i = 0; i < res.data.list.length; i++) {
        goods.push(res.data.list[i]);
      }
      that.setData({
        loadingMoreHidden: true,
        goods: goods,
      });
    })
  },
  // getCoupons: function() {
  //   var that = this;
  //   WXAPI.coupons().then(function (res) {
  //     if (res.code == 0) {
  //       that.setData({
  //         coupons: res.data
  //       });
  //     }
  //   })
  // },
  onShareAppMessage: function() {
    let that = this;  
    return {
      title: that.data.shops[0].shopName,
      path: '/pages/index/index?inviter_id=' + wx.getStorageSync('uid')
    }
  },
  // 获取某个店铺的最新公告
  getNotice: function() {
    var that = this;
    WXAPI.noticeList().then(function (res) {
      if (res.retCode === '200') {
        that.setData({
          promptText: res.data
        });
      }
    })
  },
  toShopCar(e){
    let that = this;
    let itemNo = e.currentTarget.dataset.itemno;
    for(let item of that.data.goods){
      // console.log(item)
      if (item.itemNo == itemNo){
        item.buyNumber = 1;
        for (let [index ,dots] of item.itemSkuResultDtos.entries()){
          dots.checked = false;
          dots.value = index;
          dots.text = dots.stockTitle;
        }
        // 选中的规格
        item.itemSkuResultDtos[0].checked = true;
        item.value = 0;
        item.price = item.itemSkuResultDtos[0].price;
        // 购物车选中标识
        item.checked = false; 
        item.buyMoney = parseFloat(item.price) * (item.buyNumber); 
        item.stockNo = item.itemSkuResultDtos[0].stockNo; 
        item.stockTitle = item.itemSkuResultDtos[0].stockTitle;
        item.narrowPicUrl = item.itemSkuResultDtos[0].narrowPicUrl;
        // wx.setStorage({
        //   key: 'shopCarInfo',
        //   data: item
        // })


        SETGOODS.setGoods(item, itemNo, item.itemSkuResultDtos[0].stockNo, item.shopNo);

        // wx.getStorage({
        //   key: 'shopCarInfo',
        //   success: function (res) {
        //     let resArr = res.data;
        //     resArr.push(item)
        //     wx.setStorage({
        //       key: 'shopCarInfo',
        //       data: resArr
        //     })
        //   },
        //   fail(){
        //     let resArr = [];
        //     resArr.push(item)
        //     wx.setStorage({
        //       key: 'shopCarInfo',
        //       data: resArr
        //     })
        //   }
        // })
      }
    }
  },
  toSearch: function() {
    this.setData({
      curPage: 1,
      goods:[]
    });
    //this.getGoodsList(this.data.activeCategoryId);
    this.seachGoodsList(this.data.inputVal);
  },
  onReachBottom: function() {
    this.setData({
      curPage: this.data.curPage + 1
    });
    this.seachGoodsList(this.data.activeCategoryId, true)
  },
  onPullDownRefresh: function() {
    this.setData({
      curPage: 1
    });
    this.seachGoodsList(this.data.activeCategoryId)
    wx.stopPullDownRefresh()
  },
  // onPageScroll(e){
  //   console.log(e)
  //   if (e.scrollTop > 100){
  //     this.set
  //   }
  // },
  // 以下为搜索框事件
  showInput: function () {
    this.setData({
      inputShowed: true
    });
  },
  hideInput: function () {
    this.setData({
      inputVal: "",
      inputShowed: false
    });
  },
  clearInput: function () {
    this.setData({
      inputVal: ""
    });
  },
  inputTyping: function (e) {
    this.setData({
      inputVal: e.detail.value
    });
  },
  // 获取砍价商品
  // async kanjiaGoods(){
  //   const res = await WXAPI.goods({
  //     kanjia: true
  //   });
  //   if (res.code == 0) {
  //     this.setData({
  //       kanjiaList: res.data
  //     })
  //   }
  // },
  // goCoupons: function (e) {
  //   wx.navigateTo({
  //     url: "/pages/coupons/index"
  //   })
  // },
  // pingtuanGoods(){ // 获取团购商品列表
  //   const _this = this
  //   WXAPI.goods({
  //     pingtuan: true
  //   }).then(res => {
  //     if (res.code === 0) {
  //       _this.setData({
  //         pingtuanList: res.data
  //       })
  //     }
  //   })
  // }
})